import React, { useState, useEffect, useRef } from 'react';
import { View, Input, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './index.scss';

const SearchIcon = (props) => {
    const { value, onChange } = props;
    const [data, setData] = useState('')
    const [focus, setFocus] = useState(false);
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    const inputRef = useRef(null);
    useEffect(() => {
        if (focus) {
            setData(value)
        } else {
            setData('')
        }
    }, [focus])
    // 监听键盘高度变化
    useEffect(() => {
        const handleKeyboardHeight = (res) => {
            setKeyboardHeight(res.height);
        };

        Taro.onKeyboardHeightChange(handleKeyboardHeight);
        return () => Taro.offKeyboardHeightChange(handleKeyboardHeight);
    }, []);

    // 点击图标触发输入
    const handleIconClick = () => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
        setFocus(true);
    };

    // 输入框失焦处理
    const handleBlur = () => {
        setFocus(false);
        // 延迟重置键盘高度避免闪烁
        setTimeout(() => setKeyboardHeight(0), 300);
    };

    return (
        <View className='container'>
            {/* 隐藏的输入框 */}
            <View onClick={() => handleIconClick()} className='SearchIcon_box'></View>


            {/* 自定义输入内容显示区域 */}
            <View
                className={`input-display ${focus ? 'visible' : ''}`}
                style={{ bottom: keyboardHeight > 0 ? `${keyboardHeight}px` : '-100px' }}
                onClick={handleIconClick}
            >
                {focus && <Input
                    className='display-content'
                    ref={inputRef}
                    value={data}
                    focus={focus}
                    onInput={(e) => setData(e.target.value)}
                    onBlur={handleBlur}
                    onConfirm={(e) => {
                        onChange(e.target.value)
                    }}
                    placeholder='请输入搜索内容'
                    adjustPosition={false}
                    cursorSpacing={50}
                    type='text'
                />}

                {/* <View className='keyboard-indicator'>
                    {keyboardHeight > 0 ? '键盘已显示' : '键盘已隐藏'}
                </View> */}
            </View>
        </View>
    );
};

export default SearchIcon;